package com.syh.bishe.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syh.bishe.Util.JwtUtils;
import com.syh.bishe.mapper.CompaniesMapper;
import com.syh.bishe.mapper.UserMapper;
import com.syh.bishe.pojo.Companies;
import com.syh.bishe.pojo.User;
import com.syh.bishe.service.ICompaniesService;
import com.syh.bishe.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  用户服务类
 * </p>
 *
 * @author syh
 * @since 2024-06-30
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final ICompaniesService companiesService;
    private final CompaniesMapper companiesMapper;
    @Override
    public User login(User user) {
        User one = lambdaQuery().eq(User::getEmail, user.getEmail()).eq(User::getPassword, user.getPassword()).one();
        if(one!=null){
            if(one.getLockUser()==0){
                return null;
            }
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", one.getId());
            claims.put("email", one.getEmail());
            claims.put("company", one.getCompany());
            String token = JwtUtils.generateJwt(claims);
            one.setToken(token);
            return one;
        }
        return null;
    }

    @Override
    public User register(User user) {
        int check = userMapper.check(user);
        if(check!=0){
            return null;
        }
        userMapper.insert(user);
        int checkcom = companiesMapper.check(user.getCompany());
        if(checkcom==0){
            Companies companies = new Companies().setName(user.getCompany());
            companiesService.add(companies);
        }
        return user;
    }

    @Override
    public User getByToken(String token) {
        User one = lambdaQuery().eq(User::getUsername, "syh").one();
        return one;
    }

    @Override
    public boolean reset(User user) {
        return userMapper.reset(user);
    }

    @Override
    public String getStatus(String email) {
        User user = query().eq("email", email).one();
        if(user!=null){
            return user.getLockUser().toString();
        }
        return "0";
    }
}
